//
//  BMPageViewController.m


#import "DWPageViewController.h"

@interface DWPageViewController ()<UIScrollViewDelegate>
@property (nonatomic, strong) UIViewController *contentController;
@property (nonatomic, strong) UIScrollView *scrollView;

@end

@implementation DWPageViewController

- (id)initWithViewControllers:(NSArray *)viewControllers
{
    if(self = [super init])
    {
        self.arrVC = viewControllers;
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    
    CGRect rect1 = self.view.bounds;
    
    self.scrollView = [[UIScrollView alloc] initWithFrame:rect1];
    self.scrollView.delegate = self;
    self.scrollView.scrollEnabled = NO;
    self.scrollView.pagingEnabled = YES;
    self.scrollView.bounces = NO;
    self.scrollView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    self.scrollView.showsHorizontalScrollIndicator = NO;
    self.scrollView.showsVerticalScrollIndicator = NO;
    [self.view addSubview:self.scrollView];
    
    CGSize size = self.view.bounds.size;
    self.scrollView.contentSize = CGSizeMake(size.width*[self.arrVC count], size.height);
    
    if (![self isIndexExsit:self.selectIndex]) {
        self.selectIndex = 0;
    }
    
    [self generateContentVC];
}

- (void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
    self.scrollView.contentSize = CGSizeMake(self.view.bounds.size.width * [self.arrVC count], self.view.bounds.size.height);
}


- (void)generateContentVC
{
    self.contentController = [self.arrVC objectAtIndex:self.selectIndex];
    
    CGRect rect = self.scrollView.bounds;
    rect.origin.x = rect.size.width * self.selectIndex;

    [self addChildViewController:self.contentController];
	[self.scrollView addSubview:self.contentController.view];
    self.contentController.view.frame = rect;
    self.contentController.view.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    
	[self.contentController didMoveToParentViewController:self];
    [self.scrollView setContentOffset:CGPointMake(self.scrollView.bounds.size.width*self.selectIndex, 0) animated:NO];
}

- (BOOL)isIndexExsit:(int)index
{
    int countAll = (int)[self.arrVC count];
    if (index >= 0 && index < countAll) {
        return YES;
    }
    return NO;
}

- (void)turnToViewControllerByIndex:(int)index
{
    if (![self isIndexExsit:index]) {
        return;
    }
    
    NSArray *arr = [self indexByOffset:self.scrollView.contentOffset];
    int curIndex = [[arr objectAtIndex:0] intValue];
    
    if (index == curIndex) {
        return;
    }
    [self checkIndex:@[[NSNumber numberWithInt:index]]];
    
    [self.scrollView setContentOffset:CGPointMake(self.scrollView.bounds.size.width*index, 0) animated:NO];
    [self unLoadOtherVC];
    
}

- (void)checkIndex:(NSArray *)arrIndex
{
    for (NSNumber *number in arrIndex) {
        int index = number.intValue;
        UIViewController *vc = [self.arrVC objectAtIndex:index];
        
        BOOL isNewlyAdded = ![self.childViewControllers containsObject:vc];
        if (isNewlyAdded) {
            [self addChildViewController:vc];
            
            CGRect rect = self.scrollView.bounds;
            rect.origin.x = rect.size.width * index;
            [self.scrollView addSubview:vc.view];
            vc.view.frame = rect;
            vc.view.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
        }
    }
}


- (NSArray *)indexByOffset:(CGPoint)offset
{
    CGFloat xOffset = offset.x;
    int countAll = (int)[self.arrVC count];
    
    CGFloat rate = xOffset/self.scrollView.bounds.size.width;
    
    if (rate <= 0) {
        return @[@0];
    }
    else if(rate >= countAll-1) {
        return @[[NSNumber numberWithInt:(countAll -1)]];
    }
    else
    {
    int x = floor(rate);
    int y = ceil(rate);

        if (x==y) {
            return @[[NSNumber numberWithInt:x]];
        }
        else
        {
            return @[[NSNumber numberWithInt:x],[NSNumber numberWithInt:y]];
        }
    }
    return 0;
  
}

- (void)unLoadOtherVC
{
    NSArray *arr =[self indexByOffset:self.scrollView.contentOffset];
    
        for (UIViewController *vc in self.arrVC) {
            int cuIndex = (int)[self.arrVC indexOfObject:vc];
            if ([self.childViewControllers containsObject:vc]) {
                
                BOOL result = NO;
                for (NSNumber *number in arr) {
                    if ([number intValue] == cuIndex) {
                        result = YES;
                        break;
                    }
                }
                if (!result) {
                    [vc willMoveToParentViewController:nil];
                    [vc.view removeFromSuperview];
                    [vc removeFromParentViewController];
                }
            }
        }
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    NSArray *arr = [self indexByOffset:scrollView.contentOffset];
    [self checkIndex:arr];
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(pageViewController:didScrollBetweenIndex1:index2:withPercent:)])
    {
        CGFloat percent = 0;
        CGFloat xOffset = scrollView.contentOffset.x;
        int countAll = (int)[self.arrVC count];
        
        CGFloat rate = xOffset/self.scrollView.bounds.size.width;
        if (rate < 0) {
            rate = 0;
        }
        if (rate > countAll) {
            rate = countAll;
        }
        percent = rate - floor(rate);
        
        if (arr.count == 1) {
            [self.delegate pageViewController:self didScrollBetweenIndex1:((NSNumber *)arr[0]).intValue  index2:((NSNumber *)arr[0]).intValue withPercent:percent];
        }
        else if (arr.count >= 2)
        {
            [self.delegate pageViewController:self didScrollBetweenIndex1:((NSNumber *)arr[0]).intValue  index2:((NSNumber *)arr[1]).intValue withPercent:percent];
        }
    }
}


- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    [self unLoadOtherVC];
    
    if (_delegate && [_delegate respondsToSelector:@selector(pageViewController:didScrollToIndex:)]) {
        int index = [[[self indexByOffset:scrollView.contentOffset] objectAtIndex:0] intValue];
        [_delegate pageViewController:self didScrollToIndex:index];
    }
}

- (void)setSelectIndex:(unsigned int)selectIndex
{
    _selectIndex = selectIndex;
    if (self.isViewLoaded) {
        [self turnToViewControllerByIndex:selectIndex];
    }
}


@end
